Write a function fib() that takes an integer and returns the th Fibonacci number.
Let's say our Fibonacci series is 0-indexed and starts with 0. So:
fib(0) # => 0
fib(1) # => 1
fib(2) # => 1
fib(3) # => 2
fib(4) # => 3
...
We use a bottom-up approach, starting with the 0th Fibonacci number and iteratively computing subsequent numbers until we get to .
def fib(n):
# Edge cases:
if n < 0:
raise ValueError('Index was negative. No such thing as a '
'negative index in a series.')
elif n in [0, 1]:
return n
# We'll be building the fibonacci series from the bottom up
# so we'll need to track the previous 2 numbers at each step
prev_prev = 0 # 0th fibonacci
prev = 1 # 1st fibonacci
for _ in range(n - 1):
# Iteration 1: current = 2nd fibonacci
# Iteration 2: current = 3rd fibonacci
# Iteration 3: current = 4th fibonacci
# To get nth fibonacci ... do n-1 iterations.
current = prev + prev_prev
prev_prev = prev
prev = current
return current
time and space.
This one's a good illustration of the tradeoff we sometimes have between code cleanliness and efficiency.
We could use a cute, recursive function to solve the problem. But that would cost time as opposed to time in our final bottom-up solution. Massive difference!
In general, whenever you have a recursive solution to a problem, think about what's actually happening on the call stack. An iterative solution might be more efficient.
Do you have an answer?
Wanna review this one again later? Or do you feel like you got it all?
Mark as done Pin for review laterReset editor
Powered by qualified.io